package com.example.websocket.service.impl;

import com.example.websocket.mapper.FriendsMapper;
import com.example.websocket.mapper.GroupMapper;
import com.example.websocket.pojo.dto.UserListDto;
import com.example.websocket.pojo.po.GroupPo;
import com.example.websocket.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ author 韩
 * time: 2024/3/21 11:11
 */
@Service
public class GroupServiceImpl implements GroupService {

    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private FriendsMapper friendsMapper;


    @Override
    public List<GroupPo> getOwnGroupList(String username) {
        List<Integer> groupIdList = groupMapper.getOwnGroupList(username);
        List<GroupPo> list = new ArrayList<>();
        groupIdList.forEach(
                value -> {
                    GroupPo group = groupMapper.getGroupById(value);
                    list.add(group);
                }
        );
        return list;
    }

    @Override
    public void createGroup(String groupName, String username) {
        GroupPo groupPo = new GroupPo(null, groupName,username);
        groupMapper.createGroup(groupPo);
        groupMapper.invite(Long.valueOf(groupPo.getGroup_id()),username);
    }

    @Override
    public List<String> getMemberById(Integer groupID) {
        return groupMapper.getMemberById(groupID);
    }

    @Override
    public HashSet<String> getGroupUserList(String groupId) {
        return groupMapper.getGroupUserList(groupId);
    }

    @Override
    public void invite(Integer groupId,String invitedUsername) {
        groupMapper.invite(Long.valueOf(groupId),invitedUsername);
    }

    @Override
    public List<UserListDto> getInvitedFriends(String username, Integer groupId) {
        // 查询朋友
        List<UserListDto> friends = friendsMapper.selectFriendsByUserName(username);
        // 查询群里的
        List<String> members = groupMapper.selectMemberById(groupId);

        List<UserListDto> nonGroupMembers = friends.stream()
                .filter(friend -> !members.contains(friend.getFriend_name()))
                .collect(Collectors.toList());


        return nonGroupMembers;
    }


}
